package com.woniuxy.controller;

import cn.hutool.core.util.StrUtil;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.util.MinioUtils;
import com.woniuxy.util.RespongseData;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {
    private UserService userService;
    private MinioUtils minioUtils;

    @GetMapping("/userPro")
    public String userPage(){
        return "/user/userPro";
    }

    @GetMapping("/login")
    public String loginPage(){
        return "login";
    }

    @GetMapping("/updatePsw")
    public String updatePsw(){
        return "/user/updatePassword";
    }

    //MultipartFile接受前端文件类型（图片文档
    @PostMapping("/upload")
    @ResponseBody
    public RespongseData uploadImg(MultipartFile file){
        try {
            return minioUtils.uploadFile(file,"img01");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/loginBtn")
    @ResponseBody
    public RespongseData loginBtn(@RequestBody User user, HttpSession session){

        //判断是否为空
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())){
            return new RespongseData(2000,"fail",null);
        }
        User user1 = userService.queryByUsername(user);
        //输入的账号查询不到密码
        if(user1==null){
            return new RespongseData(2001,"fail",null);
        }
        //输入的账号与密码不匹配
        if(!user1.getPassword().equals(user.getPassword())){
            return new RespongseData(2001,"fail",null);
        }

        //存储在服务器端
        session.setAttribute("userInfo",user1);
        //输入正确密码账号
        return new RespongseData(200,"ok",user1);
    }

    @PostMapping("/updateUserPsw")
    @ResponseBody
    public RespongseData updateUserPsw(@RequestBody User user){
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())){
            return new RespongseData(2000,"fail",null);
        }
        User user1 = userService.queryByUsername(user);
        //输入的账号查询不到密码
        if(user1==null){
            return new RespongseData(2001,"fail",null);
        }

        userService.updateUserPsw(user);
        return new RespongseData(200,"ok",null);
    }

    @GetMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute("userInfo");
        return "login";
    }

    @PostMapping("/inPicture")
    @ResponseBody
    public RespongseData inPicture(@RequestBody User user){
        userService.inPicture(user);
        return new RespongseData(200,"ok",null);
    }
}
